package com.mjk.common.util;

import lombok.Data;

/**
 * 外国人永久身份证解析工具类
 */
public class ForeignerIdCardUtils {
    private static final String CARD_NULL = "card is null";
    private static final String CARD_LENGTH_ERROR = "card length is error";

    private static final String CARD_START_ERROR = "card start is not 9";
    public ForeignerCardInfo parseForeignerIdCard(String idCard){
        ForeignerCardInfo cardInfo = new ForeignerCardInfo();
        if(ObjectUtils.isEmpty(idCard)){
            cardInfo.setErrorInfo(CARD_NULL);
        }
        if(idCard.length()!=15 || idCard.length()!=18){
            cardInfo.setErrorInfo(CARD_LENGTH_ERROR);
        }
        if(idCard.length() == 15){
            parse15Card(cardInfo,idCard);
        }
        if(idCard.length() == 18){
            if(idCard.startsWith("9")){
                cardInfo.setErrorInfo(CARD_START_ERROR);
            }
            parse18Card(cardInfo,idCard);
        }
        return cardInfo;
    }

    /**
     * 解析15位 国外身份证
     * @param cardInfo
     */
    public static void parse15Card(ForeignerCardInfo info,String cardInfo){
        info.setBirthDate( "19" + cardInfo.substring(6, 12));
        int genderDigit = Integer.parseInt(cardInfo.substring(14, 15));
        info.setGender((genderDigit % 2 == 0) ? "女" : "男");
        info.setNationality(cardInfo.substring(0,3));
    }

    public static void parse18Card(ForeignerCardInfo info,String cardInfo){
        info.setBirthDate(cardInfo.substring(6, 14));
        int genderDigit = Integer.parseInt(cardInfo.substring(16, 17));
        info.setGender((genderDigit % 2 == 0) ? "女" : "男");
        info.setNationality(cardInfo.substring(0,4));
    }

    /**
     * 外国身份证
     */
    @Data
    public static class ForeignerCardInfo{
        private String errorInfo;//错误信息
        private String nationality;//国籍
        private String birthDate;//生日
        private String gender;//性别
    }

}
